package com.tomato.dynamic.threadpool.core.reject;

import com.tomato.dynamic.threadpool.core.manage.AlarmManager;
import com.tomato.dynamic.threadpool.core.thread.DynamicThreadPoolExecutor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ThreadPoolExecutor;

import static com.tomato.dynamic.threadpool.common.enums.NotifyTypeEnum.REJECT;

/**
 * 拒绝策略的InvocationHandler
 * @author lizhifu
 */
@Slf4j
public class RejectedInvocationHandler implements InvocationHandler {

    private final Object target;

    public RejectedInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            ThreadPoolExecutor executor = (ThreadPoolExecutor) args[1];
            if (executor instanceof DynamicThreadPoolExecutor) {
                DynamicThreadPoolExecutor dynamicThreadPoolExecutor = (DynamicThreadPoolExecutor) executor;
                dynamicThreadPoolExecutor.incRejectCount(1);
                AlarmManager.doAlarm(dynamicThreadPoolExecutor, REJECT);
                log.info("DynamicExecutor 线程队列拒绝任务: {}", dynamicThreadPoolExecutor.getThreadPoolName());
            }
            return method.invoke(target, args);
        } catch (InvocationTargetException ex) {
            throw ex.getCause();
        }
    }
}
